package cn.hetra.hj212.service;

import cn.hetra.hj212.NettyTcpServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicBoolean;

public class ServerImpl implements InitializingBean, DisposableBean {

    private static final Logger LOGGER = LoggerFactory.getLogger(ServerImpl.class);

    private final AtomicBoolean start = new AtomicBoolean(false);
    private final AtomicBoolean stop = new AtomicBoolean(false);

    NettyTcpServer transport;

    @Autowired
    RemotingService remotingService;

    ScheduledThreadPoolExecutor scheduler;

    private Integer port =  8085;

    private Integer readerIdle = 60;
    private Integer writerIdle =  60;
    private Integer maxFrameLength = 10485760;

    public void setPort(Integer port) {
        this.port = port;
    }

    public void setReaderIdle(Integer readerIdle) {
        this.readerIdle = readerIdle;
    }

    public void setWriterIdle(Integer writerIdle) {
        this.writerIdle = writerIdle;
    }

    public void setMaxFrameLength(Integer maxFrameLength) {
        this.maxFrameLength = maxFrameLength;
    }

    @Autowired
    ObjectProvider<HJ212DataHandler> hj212DataHandler;

    public void start() {
        if (this.start.compareAndSet(false, true)) {
            this.transport.start();
        }

    }

    public void stop() {
        if (this.stop.compareAndSet(false, true)) {
            this.transport.stop();
            scheduler.shutdown();
        }

    }
    @Override
    public void afterPropertiesSet() throws Exception {
        transport = new NettyTcpServer(port,readerIdle,writerIdle,maxFrameLength,remotingService,scheduler,hj212DataHandler);
        start();
    }

    @Override
    public void destroy() throws Exception {
        stop();
    }
}
